package com.sc.admin.config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Slf4j
@EnableCaching
@Configuration
public class CacheConfig {


    @Bean
    public Caffeine<Object, Object> defaultCache() {

        return Caffeine.newBuilder()
                // 设置最后一次写入或访问后经过固定时间过期
                .expireAfterAccess(7, TimeUnit.DAYS)
                // 初始的缓存空间大小
                .initialCapacity(1000)
                // 使用自定义线程池
                // .executor(cacheExecutor)
                .removalListener(((key, value, cause) -> log.info("defaultCache key:{} removed, removalCause:{}.", key, cause.name())))
                // 缓存的最大条数
                .maximumSize(2000);
    }

    @Bean
    public Cache<String, Object> manualCacheSevenDay() {
        return Caffeine.newBuilder()
                .expireAfterAccess(10, TimeUnit.DAYS)
                .initialCapacity(500)
                .maximumSize(1000)
                .removalListener(((key, value, cause) -> log.info("manualCacheSevenDay key:{} removed, removalCause:{}.", key, cause.name())))
                .build();
    }
    @Bean
    public Cache<String, Object> manualCacheFiveSecond() {
        return Caffeine.newBuilder()
                .expireAfterAccess(5, TimeUnit.SECONDS)
                .initialCapacity(200)
                .maximumSize(1000)
                .removalListener(((key, value, cause) -> log.info("manualCacheFiveSecond key:{} removed, removalCause:{}.", key, cause.name())))
                .build();
    }

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();
        caffeineCacheManager.setCaffeine(defaultCache());
        // 不缓存空值
        caffeineCacheManager.setAllowNullValues(false);
        return caffeineCacheManager;
    }
}